#! /usr/bin/env python3

#Author: Ahmed Abdulshafy
#Time: Thursday, 27 June 2013, 7:05 PM
#Last Modification: Tuesday, 13 August 2013, 11:37 PM

import csv, re


# class cdrParser:

# 	cdr_type = None
# 	cdr_version = None



# 	def __init__(self, cdr_type="cisco", cdr_version="7.1"):
# 		self.cdr_type = cdr_type
# 		self.cdr_version = cdr_version



def strip_prefixes(num):
	pre = r'^98[12]'
	return re.split(pre, num)[-1]  #return the last element in the returned list


def determine_scenario(cdr):
	"""Determine the scenario of the call of which the CDR record is cdr.
	Inputs:
		1. cdr: CDR record of the call under consideration
	Outputs:
		1. Number indicating the identified scenario, as following:
			a. Simple Direct Call (returns 1):
				Scenario:
					1. ocg calls ocd
					2. ocd answers
					3. call terminates
				Identification:
					1. finalCalledPartyNumber = originalCalledPartyNumber
					2. (origCause_value, destCause_value) is (0, 16) or (16, 0)
	"""

	#types of scenarios
	simple_direct_call = 1

	#call manager constants
	normal_clearing = 16
	no_error = 0

	if ((cdr["origCause_value"], cdr["destCause_value"])==('0', '16') or (cdr["origCause_value"], cdr["destCause_value"])==('16', '0')) and \
	 cdr["finalCalledPartyNumber"]==cdr["originalCalledPartyNumber"]!='':
		return simple_direct_call
	else:
		return None


def cdr_parse(cdr_filename, cdr_type="cisco", cdr_version="7.1"):
	"""Parse a CDR file and returns the records as a list of dictionaries
	Inputs:
		1. cdr_file: CDR's file name to be parsed.
		2. cdr_type: string to indicate the source that generated the CDR's.
		3. cdr_version: string to indicate the version of the source that generated the CDR's.

	Outputs:
		1. List of dictionaries with each dictionary representing details
		 of a single call or None on failure.
		2. The reason of failure as a string or None if successful.
	"""

	if cdr_type=="cisco" and cdr_version=="7.1":
		#currently, only cisco call manager 7.1 CDR's are supported
		try:
			cdr_file = open(cdr_filename, 'r')
		except OSError:
			return (None, "File not found")
		else:
			cdr_reader = csv.DictReader(cdr_file)
			cdr_list = []

			#cisco call manager 7.1 constants
			valid_cdr_record_type = "1"

			for cdr in cdr_reader:
				if cdr["cdrRecordType"] != valid_cdr_record_type:
					continue   #row header
				else:
					call_id = cdr["globalCallID_callManagerId"] + "_" + cdr["globalCallID_callId"]
					clock_org = int(cdr["dateTimeOrigination"])
					clock_con = int(cdr["dateTimeConnect"])
					duration = int(cdr["duration"])
					ocg = strip_prefixes(cdr["callingPartyNumber"])    #original calling party
					ocd = strip_prefixes(cdr["originalCalledPartyNumber"])    #original called party
					
					# if ocg == "":
					# 	ocg = "n/a"
					# if ocd == "":
					# 	ocd = "n/a"


					scenario_id = determine_scenario(cdr)

					if scenario_id==1: #only return simple calls FOR NOW
						#form the return dictionary 
						d = {"scenario_id": scenario_id,
							 "call_id": call_id,
							 "t_orig": clock_org,
							 "t_con": clock_con,
							 "dur": duration,
							 "ocg": ocg,
							 "fcd": ocd}
						cdr_list.append(d)

			return (cdr_list, None)
	else:
		return (None, "Unsupported CDR type or version")


# if __name__ == "__main__":
# 	import sys
# 	(ret, err) = cdr_parse(sys.argv[1])
# 	if err != None:
# 		print(err)
# 	else:
# 		screen_wd = 80
# 		width = screen_wd//len(ret[0].items())
# 		for fname in sorted(ret[0].keys()):
# 			print(fname.center(width),end='')

# 		print("")
# 		for rec in ret:
# 			if rec["scenario_id"] == None:
# 				continue
# 			for  k in sorted(rec.keys()):
# 				print(str(rec[k]).center(width),end='')

# 			print("")
